package com.ydj.app.entity;

import com.google.gson.reflect.TypeToken;
import com.ydj.framework.mysql.BaseEntity;
import com.ydj.framework.utils.JsonUtils;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

@Getter
@Setter
@Entity
@Accessors(chain = true)
@Table(name = "chat",
        indexes = {@Index(name = "idx_userId", columnList = "userId")}
)
@org.hibernate.annotations.Table(appliesTo = "chat", comment = "对话记录表")
public class Chat extends BaseEntity {
    @Column(columnDefinition = "bigint comment '用户ID'", nullable = false)
    protected Long userId;

    // 冗余
    @Column(columnDefinition = "varchar(30) comment '用户名'")
    private String nickname;

    @Column(columnDefinition = "text comment '第一个问题'")
    private String firstQuestion;

    @Column(columnDefinition = "longtext comment '对话内容'")
    private String chatContentJson;

    @Getter
    @Setter
    @Accessors(chain = true)
    public static class ChatContentItem {
        @ApiModelProperty(value = "ChatId", example = "1234567")
        protected Long chatId;

        @ApiModelProperty(value = "角色", example = "user/assistant")
        protected String role;

        @ApiModelProperty(value = "一条记录的Markdown信息")
        protected String content;

        @ApiModelProperty(value = "时间戳")
        protected Long timestamp;

    }

    public List<ChatContentItem> getChatContentList() {
        List<ChatContentItem> result = JsonUtils.getGson().fromJson(chatContentJson, new TypeToken<List<ChatContentItem>>() {}.getType());
        if (result == null) {
            result = new ArrayList<>();
        }
        return result;
    }

    public Chat setChatContentList(List<ChatContentItem> list) {
        chatContentJson = JsonUtils.toJson(list);
        return this;
    }

    public Chat addContentItem(ChatContentItem item) {
        List<ChatContentItem> list = getChatContentList();
        list.add(item);
        setChatContentList(list);
        return this;
    }
}